// Package myexcel
// @Author: zhangdi
// @File: parse
// @Version: 1.0.0
// @Date: 2023/10/19 17:17
package myexcel

import (
	"github.com/tealeg/xlsx"
	"reflect"
	"strconv"
	"strings"
)

// ParseExcel 解析excel文件 同时根据第一行的name跟结构体name绑定
func ParseExcel(filePath string, model interface{}) ([]interface{}, error) {
	xlFile, err := xlsx.OpenFile(filePath)
	if err != nil {
		return nil, err
	}
	var result []interface{}
	header := make(map[int]string)
	modelType := reflect.TypeOf(model).Elem()

	for _, sheet := range xlFile.Sheets {
		for rowIndex, row := range sheet.Rows {
			if rowIndex == 0 {
				for colIndex, cell := range row.Cells {
					text := cell.String()
					header[colIndex] = text
				}
			} else {
				item := reflect.New(modelType).Interface()
				for colIndex, cell := range row.Cells {
					text := cell.String()
					fieldName := header[colIndex]

					for i := 0; i < modelType.NumField(); i++ {
						fieldTag := modelType.Field(i).Tag.Get("json") //xxx,omitempty
						fieldTag = strings.ReplaceAll(fieldTag, ",omitempty", "")
						if fieldTag == fieldName {
							fieldValue := reflect.ValueOf(item).Elem().Field(i)
							if fieldValue.IsValid() {
								if fieldValue.Kind() == reflect.String {
									fieldValue.SetString(text)
								} else if fieldValue.Kind() == reflect.Int {
									age, _ := strconv.Atoi(text)
									fieldValue.SetInt(int64(age))
								}
							}
							break
						}
					}
				}
				result = append(result, item)
			}
		}
	}

	return result, nil
}
